<?php
namespace app\admin\controller;

use app\admin\controller\Base;

class Admin extends Base
{

    public function index()
    {
        // 当前页码
        $page = request()->param('page', '1');
        // 每页条数
        $limit = request()->param('limit', 10);
        // 角色
        $role_id = request()->param('role_id', '');
        // 角色
        $user_name = request()->param('user_name', '');

        // 总数
        $total = model('Admin')->count();
        // 搜索条件
        $where = [];
        if ($role_id) {
            $where[] = ['role_id', '=', $role_id];
        }
        if ($user_name) {
            $where[] = ['user_name', 'like', '%'. $user_name. '%'];
        }
        $list = model('Admin')->where($where)->page($page, $limit)->select();

        // 所有角色
        $role = model('AdminRole')->column('id,title');

        // 角色名
//        foreach ($list as $key => $value) {
//            $list[$key]['role_name'] = $role[$value['role_id']];
//            $list[$key]['last_login_date'] = date('Y-m-d H:i:s', $value['last_login_time']);
//        }

        $data = [
            'total' => $total,
            'role' => $role,
            'list' => $list,
        ];

        return $this->ok($data);
    }

    public function detail()
    {
        // 当前用户
        $uid = request()->param('uid');
        $data = model('Admin')->where('uid', $uid)->find();
        return $this->ok($data);
    }

    public function save()
    {
        // 过滤字段
        $param = request()->only(['uid', 'role_id', 'user_name', 'user_password']);

        model('Admin')->saveData($param);
        return $this->ok('更新成功');
    }

    public function del()
    {
        // 过滤字段
        $uid = request()->param('uid');
        $data = model('Admin')->where('uid', $uid)->find();
        if (empty($data)) {
            $this->fail('用户不存在');
        }
        if ($data['is_super']) {
            $this->fail('用户不能删除');
        }
        $result = model('Admin')->delData($uid);
        if ($result) {
            return $this->ok('删除成功');
        } else {
            return $this->fail('删除失败');
        }
    }
}
